package com.neusoft.chatserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.neusoft.chatserver.dto.RespBean;
import com.neusoft.chatserver.entity.Message;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;

@CrossOrigin
@RestController
@RequestMapping("/chat")
public class FileController {

    private static String fileStorePath = "E:\\chat\\";

    @PostMapping(value = "/uploadFile")
    public RespBean uploadFile(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        RespBean respBean = RespBean.ok(200, "File uploaded successfully!");
        LocalDate today = LocalDate.now();
        Instant timestamp = Instant.now();
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String filenames = today + String.valueOf(timestamp.toEpochMilli()) + "."+ext;
        file.transferTo(new File(fileStorePath + filenames));
//        resUrl.put("src", "/pic/" + filenames);
        String url = "/file/" + filenames;
        respBean.setObj(url);
        return respBean;
    }

    @PostMapping("/uploadAudio")
    @ResponseBody
    public RespBean upaudio(@RequestParam(value = "file") MultipartFile file) throws IOException {
        RespBean respBean = RespBean.ok(200, "Audio uploaded successfully!");
        LocalDate today = LocalDate.now();
        Instant timestamp = Instant.now();
        String filenames = today  + String.valueOf(timestamp.toEpochMilli()) + ".mp3";
        String pathname = fileStorePath + filenames;
        file.transferTo(new File(pathname));
        String url = "/file/"+filenames;
        respBean.setObj(url);
        return respBean;
    }
}
